package com.briansteen.sketches;

import cc.creativecomputing.io.CCIOUtil;

import com.briansteen.utils.GeoPosition;
import nanoxml.XMLElement;

import java.io.*;
import java.net.*;
import java.util.*;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class TwitterApiTest {

	private String geolocationBerlin = "52.31%2C13.20%2C";
	private String geolocationNewYork = "40.47%2C-73.58%2C";
	private String geolocationDublin = "53.20%2C-6.15%2C";
	private String _searchQuery = "http://search.twitter.com/search.json?geocode=" + geolocationBerlin + "100km&rpp=100";
	private String[] _responseStrings;
	private JSONArray _twitterData;
	private ArrayList<GeoPosition> positions = new ArrayList<GeoPosition>();
	
	public TwitterApiTest() {
		// load twitter json string
		_responseStrings = CCIOUtil.loadStrings(_searchQuery);
		
		// extract content
		String jsonData = _responseStrings[0];
		jsonData = jsonData.substring(jsonData.indexOf("["), jsonData.lastIndexOf("]")+1);
		
		// parse json
		_twitterData = parseJSON(jsonData);
		
		// get tweets location
		try
		  {
			System.out.println("datasets " + _twitterData.length());
		    for(int i = 0; i < _twitterData.length(); i++) {
		      JSONObject incomObject = _twitterData.getJSONObject(i);
		      String location = incomObject.getString("location");
		      String text = incomObject.getString("text");
		      // extract tweets with lat and lon , this is hardcoded for berlin..
		      if(location.indexOf("52.") != -1) {
		    	  String[] extractedLocation = location.substring(location.indexOf("52."), location.length()).split(",");
		    	  float latitude = Float.parseFloat(extractedLocation[0]);
		    	  float longitude = Float.parseFloat(extractedLocation[1]);
		    	  System.out.println(latitude + "," + longitude + "	text: " + text);
		    	  positions.add(new GeoPosition(latitude, longitude));
		      }
		    }
		  }
		  catch(JSONException e)
		  {
		    System.out.println(e.toString());
		  }
	}
	
	// Pull data from a JSON source document (in data folder or from URL)
	JSONArray parseJSON(String source)
	{
	  JSONArray jsonArray  = null;
	  try
	  {
	    jsonArray = new JSONArray(source);
	  }
	  catch (JSONException e)
	  {
	    System.out.println(e.toString());
	  }
	  return jsonArray;  // Return the json Array
	}
    public static void main(String args[]) throws Exception {
    	TwitterApiTest main = new TwitterApiTest();
    }
}
